<template>
  {{ data.tabshow }}
  <component :is="cfg.model" v-model:window_open="data.md_mstype" title="管理指令分类">
    <template #content>
      <div style="min-height: 2000px">
        <div class="stitle">· 主分类 ·</div>
        <div class="_box0">
          <n-grid x-gap="8" y-gap="8" :cols="parseInt(cfg.sswd / 450)">
            <n-gi span="1">
              <div class="_banr">
                <div class="_2_title2" style="width: 85px">
                  <div>所属分类：</div>
                </div>
                <div class="_2_val">
                  <n-select
                    to=".v1_body"
                    v-model:value="data.cktype"
                    @update:value="set.upgroup"
                    :options="set.select_mstype"
                  />
                </div>
              </div>
            </n-gi>
            <n-gi span="1" v-if="data.cktype != null">
              <div class="_banr">
                <div class="_2_title2" style="width: 85px">
                  <div>创建子类：</div>
                </div>
                <div class="_2_val">
                  <n-flex :wrap="false">
                    <n-input v-model:value="data.new_mstype" />
                    <n-button @click="set.add_new_mstype">+</n-button>
                  </n-flex>
                </div>
              </div>
            </n-gi>
          </n-grid>
        </div>
        <div class="stitle" v-if="data.cktype != null">
          · 子分类 ·　<n-tag @click="data.showid = true">显示子类ID</n-tag>
        </div>
        <div class="_box0" v-if="data.cktype != null">
          <n-table :bordered="false" :single-line="false">
            <thead>
              <tr>
                <th v-if="data.showid == true" style="width: 200px">类ID</th>
                <th style="width: 100px">排序</th>
                <th>分类名</th>
                <th style="width: 185px">操作（修改 / 交换顺序）</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(item, key) in data.typelist">
                <td v-if="data.showid == true">{{ item._id.$oid }}</td>
                <td>
                  <div><n-input v-model:value="item.px"></n-input></div>
                </td>
                <td>
                  <div><n-input v-model:value="item.type"></n-input></div>
                </td>
                <td>
                  <div>
                    <n-space align="center">
                      <n-button @click="set.edit_type(item)" type="gt_y" size="small"
                        >提交</n-button
                      >
                      <n-button
                        v-if="data.typelist?.[key - 1] != null"
                        @click="set.edit_move(item, data.typelist?.[key - 1])"
                        type="gt_w"
                        size="tiny"
                        >↑</n-button
                      >
                      <n-button
                        v-if="data.typelist?.[key + 1] != null"
                        @click="set.edit_move(item, data.typelist?.[key + 1])"
                        type="gt_w"
                        size="tiny"
                        >↓</n-button
                      >
                    </n-space>
                  </div>
                </td>
              </tr>
            </tbody>
          </n-table>
        </div>
        <div class="nbox1" v-if="data.cktype != null">
          可以改名但不支持删除子分类，因为BOT本地写死的指令要绑定类ID
        </div>
      </div>
    </template>
  </component>

  <component :is="cfg.model" v-model:window_open="data.md_edms" title="编辑云指令">
    <template #content>
      <component
        :is="set.cmd_edit"
        :edit_typeopt="data.edit_typeopt"
        :seacmd_options="data.seacmd_options"
        type="edit"
        :data="data.edms_data"
        :set="set"
      />
    </template>
    <template #footer>
      <n-button type="gt_y" @click="set.edms_sub">确认编辑</n-button>
      <n-button type="gt_n" @click="set.edms_del">删除指令</n-button>
    </template>
  </component>

  <component :is="cfg.model" v-model:window_open="data.md_newms" title="新增云指令">
    <template #content>
      <component
        :is="set.cmd_edit"
        :edit_typeopt="data.edit_typeopt"
        :seacmd_options="data.seacmd_options"
        type="new"
        :data="data.newms_data"
        :set="set"
      />
    </template>
    <template #footer>
      <n-button type="gt_y" @click="set.newms_sub">提交指令</n-button>
    </template>
  </component>

  <m-tabs :value="data.tab" @update:value="set.tabhand" :list="data.tab_gl" />

  <div class="nbox1">
    <n-flex justify="center" align="center">
      <n-button type="gt_y" :size="cfg.sizebtn" @click="set.md_ms_newcmd"
        >新增指令</n-button
      >
      <n-button type="gt_w" :size="cfg.sizebtn" @click="set.md_ms_type"
        >管理分类</n-button
      >
    </n-flex>

    <div style="margin-top: 18px; min-height: 1050px">
      <div>
        <template v-for="item in data.tab_list">
          <div class="_typediv">
            <div class="_typename">{{ item.name }}</div>
            <n-grid x-gap="8" y-gap="8" :cols="parseInt(cfg.sswd / 210)">
              <template v-for="item2 in item.data"
                ><n-gi>
                  <div class="_cmdbox" @click="set.ckcmd(item2)">
                    <template v-if="parseInt(item2.hide) == 1">
                      <span class="_cmdtag">{{ item2.name }}</span>
                      <span class="_hidetag">(隐藏)</span>
                    </template>
                    <template v-else>
                      <span>{{ item2.name }}</span>
                    </template>
                  </div>
                </n-gi>
              </template>
            </n-grid>
          </div>
        </template>
      </div>
    </div>
  </div>
</template>
<style scoped>
._s2set {
  color: rgb(222, 196, 106);
  font-size: 0.9em;
  background-color: rgb(74 80 95);
  padding: 8px;
  border-radius: 5px;
  padding-left: 15px;
  padding-right: 15px;
  display: flex;
  gap: 15px;
}

._cmddiv {
  background-color: #2b303a;
  border-radius: 3px;
  border: solid 1px rgb(255 255 255 / 19%);
  padding: 8px;
  box-shadow: var(--nbox-boxsd);
}

._cmdtag {
  max-width: 80%;
}

._typename {
  font-size: 1.3em;
  padding-bottom: 15px;
  text-shadow: 0 0 3px #000;
  color: #63e2b7;
}

._hidetag {
  color: rgb(229 218 24 / 70%);
  font-size: 0.8em;
  padding-left: 0.3em;
}

._typediv {
  background-color: #3d4656;
  padding: 20px;
  padding-top: 10px;
  margin-bottom: 8px;
  border-radius: 3px;
  box-shadow: 0 0 2px #000000;
  border-left: solid 3px #5a6a86;
}

._cmdbox:hover {
  overflow: auto;
}

._cmdbox {
  background-color: #5a6576;
  padding: 6px;
  display: flex;
  flex-direction: row;
  border-radius: 5px;
  justify-content: space-between;
  height: 100%;
  align-items: center;
  text-shadow: 0 0 3px #000;
  cursor: pointer;
  padding-left: 12px;
}

._seabox {
  display: flex;
  gap: 2px;
  flex-direction: row;
  flex-wrap: nowrap;
}
</style>
<script>
import { cfg } from "@/cfg/cfg.js";
import cmd_edit from "./cloud_cmd_edit.vue";

export default {
  setup() {
    const set = {
      tabhand: async (id) => {
        data.tab = id;
        cfg.router.replace({
          query: {
            ...cfg.route.query,
            ct: id,
          },
        });
        set.updtab(id);
      },
      cmd_edit,
      //提交新指令
      newms_sub: async () => {
        try {
          let res = await cfg.axios.post(`${cfg.url}`, data.newms_data, {
            params: {
              t: "v2/get",
              t2: "admin/cloud_cmd",
              t3: "cmd_new_v2",
              authkey: cfg.user?.authkey,
              uid: cfg.user?.uid,
            },
          });
          if (res.data.code == 0) {
            cfg.alert.success(res.data.msg);
            data.md_newms = false;
            await set.get_list();
            set.updtab(cfg.route.query.ct);
          } else {
            cfg.alert.error({
              title: "提交失败",
              content: res.data.msg,
            });
          }
        } catch (error) {
          cfg.alert.error({
            title: "提交失败",
            content: error,
          });
        }
      },
      //新增指令按钮
      md_ms_newcmd: () => {
        data.md_newms = true;
        data.newms_data = {};
      },
      //删除编辑中的指令
      edms_del: async () => {
        cfg.alert.warning({
          title: "警告",
          content: "确定要删除该指令吗？",
          positiveText: "删除",
          negativeText: "撤销",
          draggable: true,
          onPositiveClick: async () => {
            try {
              let res = await cfg.axios.post(`${cfg.url}`, data.edms_data, {
                params: {
                  t: "v2/get",
                  t2: "admin/cloud_cmd",
                  t3: "cmd_del_v2",
                  authkey: cfg.user?.authkey,
                  uid: cfg.user?.uid,
                },
              });
              cfg.msg.success("指令删除成功");
              data.md_edms = false;
              await set.get_list();
              set.updtab(cfg.route.query.ct);
            } catch (error) {
              cfg.msg.error(error);
            }
          },
          onNegativeClick: () => {},
        });
      },
      //获取子分类的名字
      edit_v2type: (type, d) => {
        let ckg = data.tabshow;
        if (type != null) {
          ckg = type;
          d.ftype = "未分类";
        }
        data.edit_typeopt = [];
        let pushpd = {};
        for (let i = 0; i < data.group_pxys.length; i++) {
          const item = data.group_pxys[i];
          if (item.group == ckg) {
            const ftype = item.type ?? "未分类";
            if (pushpd[ftype] == null) {
              pushpd[ftype] = true;
              data.edit_typeopt.push({
                label: `${ftype}`,
                value: ftype,
              });
            }
          }
        }
        return;
      },
      edms_sub: async () => {
        try {
          let res = await cfg.axios.post(`${cfg.url}`, data.edms_data, {
            params: {
              t: "v2/get",
              t2: "admin/cloud_cmd",
              t3: "cmd_edit_v2",
              authkey: cfg.user?.authkey,
              uid: cfg.user?.uid,
            },
          });
          cfg.msg.success("指令修改成功");
          //关闭窗口
          data.md_edms = false;
          await set.get_list();
          set.updtab(cfg.route.query.ct);
        } catch (error) {
          cfg.msg.error(error);
        }
      },
      //select 攻略图片搜索
      sea_gtgl: async (text) => {
        data.seacmd_loading = true;
        clearTimeout(data.seacmd_timeout);
        data.seacmd_timeout = setTimeout(async () => {
          data.seacmd_options = [];
          let res = await cfg.axios.get(`${cfg.url}`, {
            params: {
              t: "v2/get",
              t2: "admin/cloud_cmd",
              t3: "sea_gtgl",
              authkey: cfg.user.authkey,
              uid: cfg.user.uid,
              text: text,
            },
          });
          if (res.data.code == 0) {
            const bdata = res.data.data;
            for (let i = 0; i < bdata.length; i++) {
              data.seacmd_options.push({
                label: `（分类：${bdata[i].n_dir}） ---> ${bdata[i].n_name}`,
                value: bdata[i],
              });
            }
            console.log(data.seacmd_options);
          } else {
            cfg.msg.error(res.data.msg);
          }
          data.seacmd_loading = false;
        }, 300);
      },
      //select 指令类型
      select_cmdtype: [
        { label: "攻略图片", value: "gtgl_img" },
        { label: "攻略图片+文字", value: "gtgl_img_text" },
        { label: "纯文字", value: "text" },
        { label: "图片链接", value: "imgurl" },
        { label: "文字+图片链接", value: "imgtext" },
      ],
      //修改分类参数
      edit_type: async (item) => {
        let res = await cfg.axios.get(`${cfg.url}`, {
          params: {
            t: "v2/get",
            t2: "admin/cloud_cmd",
            t3: "edit_type",
            authkey: cfg.user.authkey,
            uid: cfg.user.uid,
            data: item,
          },
        });
        if (res.data.code == 0) {
          cfg.msg.success(res.data.msg);
        } else {
          cfg.msg.error(res.data.msg);
        }
      },
      //编辑指令
      ckcmd: async (item) => {
        if (data.msloading == true) {
          cfg.msg.info("请等待加载指令");
          return false;
        } else {
          data.msloading = true;
        }
        let res = await cfg.axios.get(`${cfg.url}`, {
          params: {
            t: "v2/get",
            t2: "admin/cloud_cmd",
            t3: "loadcmd",
            authkey: cfg.user.authkey,
            uid: cfg.user.uid,
            data: item,
          },
        });
        data.edms_data = {};
        data.msloading = false;
        if (res.data.code == 0) {
          data.edms_data = res.data.data;
          if (data.edms_data.ftype == null) {
            data.edms_data.ftype = "未分类";
          }
          data.md_edms = true;
        } else {
          cfg.msg.error(res.data.msg);
        }
      },
      //交换排序
      edit_move: async (item, item2) => {
        let res = await cfg.axios.get(`${cfg.url}`, {
          params: {
            t: "v2/get",
            t2: "admin/cloud_cmd",
            t3: "edit_move",
            authkey: cfg.user.authkey,
            uid: cfg.user.uid,
            data: item,
            data2: item2,
          },
        });
        if (res.data.code == 0) {
          set.upgroup(data.cktype);
        } else {
          cfg.msg.error(res.data.msg);
        }
      },
      //把数组改为obj排序
      repx: (arr) => {
        let obj = {};
        for (let i = 0; i < arr.length; i++) {
          const d = arr[i];
          if (obj[d.group] == null) {
            obj[d.group] = {};
          }
          if (obj[d.group][d.type] == null) {
            obj[d.group][d.type] = parseInt(d.px) ?? 9999;
          }
        }
        return obj;
      },
      //选择并获取云指令分类
      upgroup: async (group) => {
        let res = await cfg.axios.get(`${cfg.url}`, {
          params: {
            t: "v2/get",
            t2: "admin/cloud_cmd",
            t3: "list_type",
            authkey: cfg.user.authkey,
            uid: cfg.user.uid,
            group: group,
          },
        });
        if (res.data.code == 0) {
          data.typelist = res.data.data;
        } else {
          cfg.msg.error(res.data.msg);
        }
      },
      //创建云指令分类
      add_new_mstype: async () => {
        if (data.cktype == null) {
          cfg.msg.error("请先选择云指令所属分类");
          return false;
        }
        if (data.new_mstype == null) {
          cfg.msg.error("请输入子分类名称");
          return false;
        }
        let res = await cfg.axios.get(`${cfg.url}`, {
          params: {
            t: "v2/get",
            t2: "admin/cloud_cmd",
            t3: "new_type",
            authkey: cfg.user.authkey,
            uid: cfg.user.uid,
            group: data.cktype,
            type: data.new_mstype,
          },
        });
        if (res.data.code == 0) {
          set.upgroup(data.cktype);
          cfg.msg.success("创建云指令分类成功");
        } else {
          cfg.msg.error(res.data.msg);
        }
      },
      select_mstype: [
        {
          label: "会战",
          value: "会战",
        },
        {
          label: "攻略",
          value: "攻略",
        },
        {
          label: "娱乐",
          value: "娱乐",
        },
        {
          label: "管理",
          value: "管理",
        },

        {
          label: "其他",
          value: "其他",
        },
        {
          label: "mhy(米哈游)",
          value: "mhy",
        },

        {
          label: "pcr(公主连结)",
          value: "pcr",
        },
        {
          label: "ba(碧蓝档案)",
          value: "ba",
        },
        {
          label: "其他游戏",
          value: "game",
        },
      ],
      md_ms_type: () => {
        data.md_mstype = true;
      },
      updtab: (type) => {
        data.tab_list = {};
        for (let i = 0; i < data.cmd_list.length; i++) {
          if (data.cmd_list[i].group == type) {
            const item = data.cmd_list[i];
            const ftype = item.ftype ?? "未分类";
            const group = item.group ?? "未分组";
            if (data.tab_list[ftype] == null) {
              data.tab_list[ftype] = {
                name: ftype,
                data: [],
                px: data.group_px?.[group]?.[ftype] ?? 9999,
              };
            }
            data.tab_list[ftype].data.push(data.cmd_list[i]);
          }
        }
        // 对obj data.tab_list遍历
        for (const key in data.tab_list) {
          const item = data.tab_list[key];
          item.data = item.data.sort((a, b) => {
            return a.px - b.px;
          });
        }
        //对obj data.tab_list根据px排序
        data.tab_list = Object.values(data.tab_list).sort((a, b) => {
          return a.px - b.px;
        });
      },
      get_list: async () => {
        let res = await cfg.axios.get(`${cfg.url}`, {
          params: {
            t: "v2/get",
            t2: "admin/cloud_cmd",
            t3: "list_v2",
            authkey: cfg.user.authkey,
            uid: cfg.user.uid,
          },
        });

        if (res.data.code == 0) {
          const datax = res.data.data;
          data.cmd_list = datax.cmd;
          data.group_list = datax.msgroup;
          data.tab_gl = [];
          //循环obj
          for (const key in data.group_list) {
            const item = data.group_list[key];
            data.tab_gl.push({
              name: item.value,
              title: item.value + "分类",
            });
          }
          data.group_pxys = datax.group;
          data.group_px = set.repx(datax.group);
        } else {
          cfg.msg.error(res.data.msg);
        }
      },
    };
    let data = reactive({
      tab: cfg.route.query.ct ?? "会战",
      cktype: null,
      md_edms: false,
      md_newms: false,
      seacmd_options: [],
      edms_data: {},
      edit_typeopt: [],
      seacmd_loading: false,
      newms_data: {},
      seacmd_timeout: null,
      showid: false,
      msloading: false,
      cmd_list: [],
      typelist: [],
      md_mstype: false,
      group_list: [],
      tab_gl: [],
      tab_list: [],
      group_px: {},
      group_pxys: [],
    });
    onMounted(async () => {
      await set.get_list();
      set.tabhand(data.tab);
    });
    return { data, cfg, set };
  },
};
</script>
